<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" class="filter-item"  style="width: 200px;" :placeholder="$t('table.rank_name')" v-model="listQuery.rank_name">
      </el-input>

      <el-select clearable class="filter-item" style="width: 150px"  :placeholder="$t('table.rank_type')" v-model="listQuery.rank_type">
        <el-option v-for="item in rankTypeOptions" :key="item.key" :label="item.display_name" :value="item.key">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">{{$t('table.add')}}</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column :label="$t('table.rank_name')"  width="200px" >
        <template slot-scope="scope">
          <el-tag>{{scope.row.rank_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('table.rank_type')" width="150px" >
        <template slot-scope="scope">
          <el-tag>{{scope.row.rank_type | rankTypeFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.rank_remark')" min-width="200px">
        <template slot-scope="scope">
          <span>{{scope.row.rank_remark}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('table.actions')"  class-name="small-padding fixed-width" min-width="200px">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button size="mini" type="success" @click='handleRoles(scope.row)' >{{$t('table.privileges')}}</el-button>
          <el-button size="mini" type="success" @click='handleShowViewDialog(scope.row)' >粒度</el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleDelete(scope.row)">{{$t('table.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form  :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item :label="$t('table.rank_name')" prop="rank_name">
          <el-input v-model="temp.rank_name"></el-input>
        </el-form-item>
        
        <el-form-item :label="$t('table.rank_type')" prop="rank_type">
          <el-select class="filter-item" v-model="temp.rank_type" placeholder="Please select">
            <el-option v-for="item in rankTypeOptions" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.rank_remark')">
          <el-input v-model="temp.rank_remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
  </el-dialog>
    <el-dialog title="权限粒度" :visible.sync="dialogViewInfoVisible">
      <template>
        <div>
          <span>权限:</span>
          <el-select clearable class="filter-item" style="width: 150px" placeholder="请选择" v-model="view_content" @change="handleViewContent">
            <el-option v-for="item in viewContentOptions" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </div>
        <div>
          <div style="margin: 15px 0;">工作室</div>
          <div style="margin: 15px 0 0 20px;">
            <el-checkbox :indeterminate="isIndeterminateOffices" v-model="checkAllOffices" @change="handleCheckAllOfficesChange">全选</el-checkbox>
            <el-checkbox-group v-model="checkedOffices" @change="handleCheckedOfficesChange">
              <el-checkbox v-for="item in offices" :label="item.key" :key="item.key">{{item.display_name}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div>
          <div style="margin: 15px 0;">部门</div>
          <div style="margin: 15px 0 0 20px;">
            <el-checkbox :indeterminate="isIndeterminateDepts" v-model="checkAllDepts" @change="handleCheckAllDeptsChange">全选</el-checkbox>
            <el-checkbox-group v-model="checkedDepts" @change="handleCheckedDeptsChange">
              <el-checkbox v-for="item in depts" :label="item.key" :key="item.key">{{item.display_name}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogViewInfoVisible = false">{{$t('table.cancel')}}</el-button>
          <el-button type="primary" @click="saveViewRole">保存</el-button>
      </div>
      </template>
    </el-dialog>
    <el-dialog title="权限分配" :visible.sync="dialogRoleVisible">
      <template>
        <el-transfer
          v-model="rolesOfRankData"
          filterable
          :titles="['未分配权限', '已有权限']"
          :button-texts="['移除', '分配']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          @change="handleChange"
          :data="rolesData">
          <span slot-scope="{ option }"> <div :title="option.label">{{ option.label }}</div></span>
        </el-transfer>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import API from '@/utils/backend_api'
import waves from '@/directive/waves' // 水波纹指令
import Static_Data from '@/data/index'
const rankTypeOptions = [
  { key: '0', display_name: '普通' },
  { key: '9', display_name: '管理' }
]
const viewContentOptions = [
  { key: 'VIEW_CLIENT', display_name: '可视客户' },
  { key: 'VIEW_PROJECT', display_name: '可视项目' },
  { key: 'VIEW_EMPLOYEE', display_name: '可视员工业绩' },
  { key: 'CHECK_ALL', display_name: '审批' }
]

const rankTypeKeyValue = rankTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'rank',
  components: { },
  directives: {
    waves
  },
  data() {
    return {
      checkAllOffices: false,
      checkedOffices: [],
      offices: Static_Data.office,
      isIndeterminateOffices: true,
      isIndeterminateDepts: true,
      checkAllDepts: false,
      checkedDepts: [],
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        rank_name: undefined,
        rank_type: undefined,
        sort: '+id'
      },
      view_content: '',
      viewContentOptions,
      rankTypeOptions,
      temp: {
        id: undefined,
        rank_name: '',
        rank_type: '',
        rank_remark: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogRoleVisible: false,
      dialogViewInfoVisible: false,
      rolesOfRankData: [],
      rolesData: [],
      op_rank_id: '',
      rules: {
        rank_name: [{ required: true, message: 'name is required' }],
        rank_type: [{ required: true, message: 'type is required' }]
      },
      downloadLoading: false
    }
  },
  filters: {
    rankTypeFilter(type) {
      return rankTypeKeyValue[type]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleViewContent(val) {
      console.log(val)
      console.log(this.view_content)
      this.checkedOffices = []
      this.checkedDepts = []
      API.rank.getRankRoles(this.op_rank_id).then(response => {
        if (response && response.data) {
          response.data.map(item => {
            if (item.indexOf(val + '_' + 'DEPT') >= 0) {
              this.checkedDepts.push(item.replace(val + '_' + 'DEPT_', ''))
            }
            if (item.indexOf(val + '_' + 'OFFICE') >= 0) {
              this.checkedOffices.push(item.replace(val + '_' + 'OFFICE_', ''))
            }
          })
        }
        console.log(this.checkedDepts)
      })
    },
    getList() {
      this.listLoading = true
      API.rank.all(this.listQuery).then(response => {
        this.list = response.data
        if (response.headers && response.headers['x-total-count']) {
          this.total = Number(response.headers['x-total-count'])
        }
        this.listLoading = false
      })
      API.department.all(this.listQuery).then(response => {
        console.log(response)
        response.data.map(item => {
          if (item.department_type === '1') {
            this.depts.push({ key: item.id, display_name: item.department_name })
          }
        })

        this.listLoading = false
      })
    },
    handleChange(value, direction, movedKeys) {
      if (direction === 'left') {
        console.log(movedKeys)
        movedKeys.map(item => {
          API.rank.del_role_from_rank(this.op_rank_id, item).then(response => {
            console.log('del_role_from_rank:' + item)
          })
        })
        // 移除
      } else if (direction === 'right') {
        // 分配
        console.log(movedKeys)
        movedKeys.map(item => {
          API.rank.add_role_to_rank(this.op_rank_id, item).then(response => {
            console.log('add_role_from_rank:' + item)
          })
        })
      } else {
        console.log(direction)
      }
    },
    saveViewRole() {
      if (this.view_content === '') {
        this.$message({
          message: '可视信息不能为空',
          type: 'warning'
        })
        return
      }
      API.rank.add_role_area_to_rank(this.op_rank_id, {
        content: this.view_content,
        depts: JSON.stringify(this.checkedDepts),
        offices: JSON.stringify(this.checkedOffices)
      }).then(response => {
        this.$message({
          message: '保存成功！',
          type: 'success'
        })
      })
    },
    handleCheckAllOfficesChange(val) {
      this.checkedOffices = val ? this.offices.map(item => item.key) : []
      this.isIndeterminateOffices = false
    },
    handleCheckedOfficesChange(value) {
      const checkedCount = value.length
      this.checkAllOffices = checkedCount === this.offices.length
      this.isIndeterminateOffices = checkedCount > 0 && checkedCount < this.offices.length
    },
    handleCheckAllDeptsChange(val) {
      this.checkedDepts = val ? this.depts.map(item => item.key) : []
      this.isIndeterminateDepts = false
    },
    handleCheckedDeptsChange(value) {
      const checkedCount = value.length
      this.checkAllDepts = checkedCount === this.depts.length
      this.isIndeterminateDepts = checkedCount > 0 && checkedCount < this.depts.length
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        rank_name: '',
        rank_remark: '',
        rank_type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleRoles(data) {
      // 移除所有角色数据
      this.rolesData.splice(0, this.rolesData.length)
      // 设置当前操作的职位
      this.op_rank_id = data.id
      API.rbac.roles().then(response => {
        console.log('roles then')
        console.log(response.data)
        if (response.data && response.data.length > 0) {
          response.data.map(item =>
            this.rolesData.push({ key: item.id, label: item.rolename })
          )
        }
        this.rolesData = this.rolesData.sort((a, b) => (a.key[0] < b.key[0]))
        API.rank.get_roles_for_rank(data.id).then(response => {
          this.rolesOfRankData.splice(0, this.rolesOfRankData.length)
          response.data.map(item => {
            if (this.rolesData.some(role_item => (role_item.key === item))) {
              this.rolesOfRankData.push(item)
            }
          })
        })
      })

      this.dialogRoleVisible = true
    },
    handleShowViewDialog(data) {
      this.op_rank_id = data.id
      this.view_content = ''
      this.checkedOffices = []
      this.checkedDepts = []
      this.dialogViewInfoVisible = true
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          API.rank.add(this.temp).then((response) => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          API.rank.update(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.rank.del(row.id).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$notify({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
